package com.xinchen.aiowaste.ui.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import android.widget.TextView
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import com.maple.common.serialPort.SerialPortHelper
import com.maple.model.entity.aio.FacilityListEntity
import com.maple.model.entity.aio.StorehouseListEntity
import com.maple.model.entity.aio.WarehouseListEntity
import com.maple.model.entity.aio.WasteListEntity
import com.maple.utils.const.ConstKey
import com.maple.utils.store.AioDBHelper
import com.maple.utils.util.LogUtils
import com.maple.utils.util.UIUtils.Companion.serializable
import com.serial.port.kit.core.common.TypeConversion
import com.serial.port.manage.data.WrapReceiverData
import com.serial.port.manage.data.WrapSendData
import com.serial.port.manage.listener.OnDataPickListener
import com.serial.port.manage.listener.OnDataReceiverListener
import com.xinchen.aiowaste.R
import com.xinchen.aiowaste.base.BaseActivity
import com.xinchen.aiowaste.ui.adapter.FacilitySpinnerAdapter
import com.xinchen.aiowaste.ui.adapter.StorehouseSpinnerAdapter
import com.xinchen.aiowaste.ui.adapter.WarehouseSpinnerAdapter
import com.xinchen.aiowaste.vm.InboundWeightViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import java.util.WeakHashMap

class InboundWeightActivity : BaseActivity() {

    private var spFacility: Spinner? = null
    private var spWarehouse: Spinner? = null
    private var spStorehouse: Spinner? = null

    private var tvWasteType: TextView? = null
    private var tvWasteCode: TextView? = null
    private var btnPeel: Button? = null
    private var btnReset: Button? = null
    private var btnInbound: Button? = null

    private var etIndustryName: EditText? = null
    private var etTransformName: EditText? = null

    private val viewModel by viewModels<InboundWeightViewModel>()

    private var type: String? = ""
    private var data: WasteListEntity.DataList? = null

    private var facilityData: FacilityListEntity.Data? = null
    private var warehouseData: WarehouseListEntity.Data? = null
    private var storehouseData: StorehouseListEntity.Data? = null
    override fun getLayoutId(): Int = R.layout.activity_inbound_weight

    private val facilityAdapter: FacilitySpinnerAdapter by lazy {
        FacilitySpinnerAdapter(this)
    }

    private val warehouseAdapter: WarehouseSpinnerAdapter by lazy {
        WarehouseSpinnerAdapter(this)
    }

    private val storehouseAdapter: StorehouseSpinnerAdapter by lazy {
        StorehouseSpinnerAdapter(this)
    }
    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        setTitle("入库称重")
        showClockTime()
        onBackClick()
        spFacility = findViewById(R.id.sp_facility)
        spFacility?.onItemSelectedListener = object : OnItemSelectedListener{
            override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, i: Int, l: Long) {
                val item: FacilityListEntity.Data = facilityAdapter.getItem(i) as FacilityListEntity.Data
                facilityData = item
            }
            override fun onNothingSelected(adapterView: AdapterView<*>?) {}
        }
        spFacility?.adapter = facilityAdapter
        spWarehouse = findViewById(R.id.sp_warehouse)
        spWarehouse?.onItemSelectedListener = object : OnItemSelectedListener{
            override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, i: Int, l: Long) {
                runBlocking {
                    delay(100L)
                }
                val item: WarehouseListEntity.Data = warehouseAdapter.getItem(i) as WarehouseListEntity.Data
                warehouseData = item
                viewModel.getStorehouseList(item.repositoryId)
            }
            override fun onNothingSelected(adapterView: AdapterView<*>?) {}
        }
        spWarehouse?.adapter = warehouseAdapter
        spStorehouse = findViewById(R.id.sp_storehouse)
        spStorehouse?.onItemSelectedListener = object : OnItemSelectedListener{
            override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, i: Int, l: Long) {
                val item: StorehouseListEntity.Data = storehouseAdapter.getItem(i) as StorehouseListEntity.Data
                storehouseData = item
            }
            override fun onNothingSelected(adapterView: AdapterView<*>?) {}
        }
        spStorehouse?.adapter = storehouseAdapter

        etIndustryName = findViewById(R.id.et_industry_name)
        etTransformName = findViewById(R.id.et_transform_name)

        val industryName = AioDBHelper.getIndustryName()
        if(!TextUtils.isEmpty(industryName)) {
            etIndustryName?.setText(industryName)
        }
        val transformName = AioDBHelper.getTransformName()
        if(!TextUtils.isEmpty(transformName)) {
            etTransformName?.setText(transformName)
        }

        btnPeel = findViewById(R.id.btn_peel)
        btnPeel?.setOnClickListener {

        }
        btnReset = findViewById(R.id.btn_reset)
        btnReset?.setOnClickListener {

        }
        btnInbound = findViewById(R.id.btn_inbound)
        btnInbound?.setOnClickListener {
            val industryName = etIndustryName?.text.toString().trim()

            if(TextUtils.isEmpty(industryName)) {
                showToast("请输入产生部门经办人")
                return@setOnClickListener
            }
            AioDBHelper.saveIndustryName(industryName)

            val transformName = etTransformName?.text.toString().trim()
            if(TextUtils.isEmpty(transformName)) {
                showToast("请输入运送部门经办人")
                return@setOnClickListener
            }
            AioDBHelper.saveTransformName(transformName)



            val params: WeakHashMap<String, Any> = WeakHashMap()

            data?.run {
                params.put("produceHandledBy", industryName)
                params.put("transportHandledBy", transformName)
                params.put("weightNumber", viewModel.scalesNo)
                params.put("wasteId", id)
                params.put("entId", viewModel.entId)
                params.put("userId", viewModel.userId)
//                params.put("weight", "净重")
                params.put("weight", "1")
                params.put("wasteName", wasteName)
                params.put("wasteCode", wasteCode)
                params.put("wasteType", wasteType)
                params.put("wid", warehouseData?.repositoryId)
                params.put("wname", warehouseData?.repositoryName)
                params.put("sid", storehouseData?.spaceId)
                params.put("sname", storehouseData?.spaceName)
                params.put("produceFacilitiesCode", facilityData?.facilityCode)
                params.put("produceFacilitiesName", facilityData?.czFacilityName)
            }

            LogUtils.logGGQ("产生设施：${facilityData?.czFacilityName}")
            LogUtils.logGGQ("贮存设施：${warehouseData?.repositoryName}")
            LogUtils.logGGQ("贮存库位：${storehouseData?.spaceName}")


            viewModel.inboundSubmit(params)
        }
    }
    override fun initData(savedInstanceState: Bundle?) {
        viewModel.defUI.showDialog.observe(this, Observer {
            showLoading()
        })

        viewModel.defUI.dismissDialog.observe(this, Observer {
            dismissLoading()
        })

        viewModel.defUI.toastEvent.observe(this, Observer {
            showToast(it)
        })


        viewModel.facilityListData.observe(this, Observer{
            facilityData = it.first()
            facilityAdapter.setData(it)
        })

        viewModel.warehouseListData.observe(this, Observer{
            warehouseData = it.first()
            warehouseAdapter.setData(it)
        })

        viewModel.storehouseListData.observe(this, Observer{
            storehouseData = it.first()
            storehouseAdapter.setData(it)
        })

        viewModel.warehousData.observe(this, Observer {
            val bundle: Bundle = Bundle()
            bundle.putString(ConstKey.BundleKey.EXTRA_TYPE,type)
            bundle.putString(ConstKey.BundleKey.EXTRA_CODE,it)
            onStartActivity(PrintLabelActivity::class.java,bundle = bundle)
        })

        getBundle()?.let {
            type = it.getString(ConstKey.BundleKey.EXTRA_TYPE).toString()
            data = it.serializable(ConstKey.BundleKey.EXTRA_OBJ)
            viewModel.getFacilityList()
            viewModel.getWarehouseList()
            LogUtils.logGGQ("type:${type}")
            data?.run {
                LogUtils.logGGQ("wasteName:${wasteName}")
                LogUtils.logGGQ("wasteType:${wasteType}")
                LogUtils.logGGQ("wasteCode:${wasteCode}")
                tvWasteType?.text = wasteType
                tvWasteCode?.text = wasteCode
            }
        }

        if (!SerialPortHelper.portManager.isOpenDevice) {
            val open = SerialPortHelper.portManager.open()
            LogUtils.logGGQ("串口打开${if (open) "成功" else "失败"}")
        }

    }

    override fun onResume() {
        super.onResume()
        // 增加统一监听回调
        SerialPortHelper.portManager.addDataPickListener(onDataPickListener)
    }

    override fun onPause() {
        super.onPause()
        // 移除统一监听回调
        SerialPortHelper.portManager.removeDataPickListener(onDataPickListener)
    }

    private val onDataPickListener: OnDataPickListener = object : OnDataPickListener {
        override fun onSuccess(data: WrapReceiverData) {
            LogUtils.logGGQ("统一响应数据 成功：${TypeConversion.bytes2HexString(data.data)}")
            send()
        }

        override fun onFailed(wrapSendData: WrapSendData, msg: String) {
            super.onFailed(wrapSendData, msg)
            LogUtils.logGGQ("统一响应数据 失败：${msg}")
        }

        override fun onTimeOut() {
            super.onTimeOut()
            LogUtils.logGGQ("统一响应数据 onTimeOut")
        }
    }

    private fun send() {
//        SerialPortHelper.portManager.send(WrapSendData(SenderManager.getSender().sendStartDetect()),
        SerialPortHelper.portManager.send(WrapSendData("024303".toByteArray()),
            object : OnDataReceiverListener {
                override fun onSuccess(data: WrapReceiverData) {
                    LogUtils.logGGQ("响应数据：${TypeConversion.bytes2HexString(data.data)}")
                }

                override fun onFailed(wrapSendData: WrapSendData, msg: String) {
                    LogUtils.logGGQ("发送数据: ${TypeConversion.bytes2HexString(wrapSendData.sendData)}, $msg")
                }

                override fun onTimeOut() {
                    LogUtils.logGGQ("发送或者接收超时")
                }
            })
    }
}